package com.oneonefive.educationsystem.controller;

import com.oneonefive.educationsystem.domain.User;
import com.oneonefive.educationsystem.dto.Result;
import com.oneonefive.educationsystem.service.UserService;
import com.oneonefive.educationsystem.vo.UserVo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @PostMapping(value = "/hello")
    @PreAuthorize("hasAuthority('teacher') or hasAuthority('student')")
    public Result hello() {
        System.out.println("111");
        return Result.fail("hello");
    }

    @PostMapping(value = "/login")
    public Result login(@RequestBody User user) {
        return userService.login(user);
    }

    @PostMapping
    @PreAuthorize("hasAuthority('admin')")
    public Result userSave(@RequestBody User user) {
        Result legitimacy = userService.legitimacy(user);
        if (!legitimacy.getSuccess()) {
            return legitimacy;
        }
        return userService.saveUser(user);
    }

    @DeleteMapping("/{userId}")
    @PreAuthorize("hasAuthority('admin')")
    public Result userDelete(@PathVariable Integer userId) {
        boolean success = userService.removeById(userId);
        if (success) {
            return Result.ok("user删除成功");
        }
        return Result.fail("user删除失败");
    }

    @PutMapping
    @PreAuthorize("hasAuthority('admin')")
    public Result userUpdate(@RequestBody User user) {
        if (user.getPassword().equals("123456")){
            BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
            user.setPassword(bCryptPasswordEncoder.encode("123456"));
        }
        Result legitimacy = userService.legitimacy(user);
        if (!legitimacy.getSuccess()) {
            return legitimacy;
        }
        boolean success = userService.updateById(user);
        if (success) {
            return Result.ok("user修改成功");
        }
        return Result.fail("user修改失败");
    }

//    //data:List<User>
//    @PostMapping( "/admin/1")
//    public Result userList(@RequestBody User user) {
//        return userService.userList(user);
//    }

    //查出全部不是student的user:job!=3
    @PostMapping("/notStu")
    public Result noStudentList(@RequestBody UserVo userVo) {
        return userService.noStudentList(userVo);
    }

    @DeleteMapping("/allDelete")
    @PreAuthorize("hasAuthority('admin')")
    public Result allDelete(@RequestBody List<Integer> list) {
        for (Integer integer : list) {
            boolean b = userService.removeById(integer);
            if (!b) {
                return Result.fail(integer + "删除失败");
            }
        }
        return Result.ok("批量删除成功");
    }
}
